<?php
namespace Macaca\Controller\Admin;

use Macaca\Module;
use Macaca\View;

//use Module\Index\Main;

class Index extends Base {

    public function actionIndex() {
        //这个是用伪静态的方式，可以不用路由配置，
        //但是仍然要经过框架解析，所以速度受到限制
        //但是有个优点是对那些需要验证用户状态的路由就必须使用这种方式了
        $cacheFile = $this->app->DIR . '/temp/static/admin/index.txt';
        if (is_file($cacheFile)) {
            $index = file_get_contents($cacheFile);
        }
        else {
            $index = $this->getIndex();
            dir_check(dirname($cacheFile));
            file_put_contents($cacheFile, $index);
        }

        $user = new Module\Admin\User($this->app);
        $userName = $user->getFieldFromSession('uname');
        $index = str_replace('{{user_name}}', $userName, $index);
        $this->response->setBody($index);
    }

    public function actionMain() {
        $view = new View\Admin\Main($this->app);
        $module = new Module\Admin\Main($this->app);
        $data['title'] = 'Macaca 企业建站系统管理首页';
        $this->response->setBody($view->render($data + $module->getServerInfo()));
    }

    public function actionAbout() {
        //这里用的是全静态方式，生成页面后就不用框架解析了，所以是脱离框架运行的非常快！
        //全静态虽快，但是有两个先决条件：
        // 1 是路由支持，指向全静态的目录，如 /public/admin/about 既是路由，也是全静态文件路径。
        // 2 是配置或代码中支持生成全静态文件，这里就是代码硬编码生成全静态文件。
        $staticFile = $this->app->INDEX_ROOT_DIR . '/public/admin/about.html';
        $view = new View\Admin\About($this->app);
        $data['title'] = '关于 Macaca 企业建站系统';
        $data['macaca_version'] = $this->app->VERSION;
        $about = $view->render($data);

        dir_check(dirname($staticFile));
        file_put_contents($staticFile, $about);
        $this->response->setBody($about);
    }

    public function actionCacheClear() {
        //清除缓存
        $this->writeLine('正在清除缓存...');
        $this->app->cache()->clear();
        //清除临时目录
        $this->writeLine('正在清除临时目录...');
        $this->app->clearTempDir();
        //清除全静态目录
        $this->writeLine('正在清除全静态目录...');
        $staticDir = $this->app->INDEX_ROOT_DIR . '/public';
        dir_check($staticDir);
        dir_delete($staticDir);
        //        session_destroy();
        $this->writeLine('缓存清除完成。');
    }

    private function getIndex() {
        $app = $this->app;
        $view = new View\Admin\Index($app);
        $linker = $this->linker;

        $data['title'] = 'Macaca 企业建站系统 管理后台';
        $data['url_index'] = $linker->toFix('/');
        $data['url_cache_clear'] = $linker->toFix('/admin/cache/clear');
        $data['url_about'] = $linker->toFix('/public/admin/about');
        $data['url_logout'] = $linker->toFix('/admin/user/logout');
        $data['url_main'] = $linker->toFix('/admin/main');
        $data['url_user_edit_me'] = $linker->toFix('/admin/user/edit/me');

        $index = new Module\Admin\Index($app);
        $data['nav'] = $index->getNav();

        return $view->render($data);
    }

} 